function generateUUID(){
    var d = new Date().getTime();
    var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        var r = (d + Math.random()*16)%16 | 0;
        d = Math.floor(d/16);
        return (c=='x' ? r : (r&0x3|0x8)).toString(16);
    });
    return uuid;
};

var directives = angular.module('MyDirectives',[]);

directives.directive("question", function(){
    var dir= {
    restrict: "E",
    templateUrl: "/part/directives/question.html",
    scope:{
        qTpl: "=question",
        finalAnswers: "=answers",
    },

    //qTpl (Question Template), q (holds answered questions)
    createModelAnswers : function(qTpl, q){
        //create copy from template answers to final answers
        for(i=0; i<qTpl.Answers.length; i++){
            var answerTpl= qTpl.Answers[i];
            //copy template answers to choices object
            if(!q.Choices[answerTpl.Id]){ 
                q.Choices[answerTpl.Id] = {Wght: answerTpl.Wght, Text:null, Checked:false}
            }
        }

    },

    controller: function($scope){
        //if(!$scope.answers) $scope.answers = {}
        var qTpl = $scope.qTpl;
        var id = qTpl.Id;
        $scope.q = $scope.finalAnswers[id];

        if(!$scope.q){
            $scope.finalAnswers[id] = $scope.q = {Single:null, Choices:{}, Wght:qTpl.Wght}
            dir.createModelAnswers(qTpl, $scope.q) // add model answers to final question answers
        }


    },

    link: function(scope, elem, attr){

    }

    };
return dir
});



directives.directive("org", function(){
    var dir = {
    restrict: "E",
    templateUrl: "/part/directives/org.html",
    scope:{
        users: "=",
        org: "=",
        saveOrg: "=",
        proxy: "=",
    },
    controller: function($scope){
        $scope.editMode = false;
        $scope.show = true; // org tag is visible, affected by filterOrg event 
        if(!$scope.org.Name){
            $scope.editMode = true;
        }
        $scope.userSelected = function(user){
            console.log("user selected")
            console.log(user)
            $scope.selectedUser = user;
        };
        $scope.update = function(){
            console.log($scope.user)
            $scope.org.UserEmail = $scope.user.Email
            //TODO update user with profile password if needed 
        };

        $scope.save = function(){
            console.log($scope.proxy);
            $scope.proxy.saveOrg($scope.org);
            $scope.editMode = !$scope.editMode
        };
        $scope.toggle = function(){
            $scope.editMode = !$scope.editMode
        }

        for(var i=0; i< $scope.users.length; i++){
            var user = $scope.users[i];
            if(user.Email == $scope.org.UserEmail){
                $scope.user = user;
                break;
            }
        }

        $scope.$on("closeAllOrgs", function(){$scope.editMode = false; })
        $scope.$on("openAllOrgs", function(){$scope.editMode = true; })
        $scope.$on("filterOrg", function(e, data){
            if(! data || !data.re || !data.field){$scope.show= true; return;}

            data.re.exec($scope.org[data.field])? $scope.show = true:  $scope.show = false;
        
        })

    },


    };

    return dir;
});

directives.directive("semCheckbox", function(){
    return {
        restrict: "A",
        //transclude: true,
        scope: {checked: '@', model: '=ngModel'},
        link: function(scope, element, attrs){
            var input = element.children()[0];
            console.log(input);

            var toggle = function(){
                //reverse selection and update child input
                scope.checked  = scope.model = !scope.checked;
                scope.checked == true 
                    ? input.setAttribute('checked', 'true') 
                    : input.removeAttribute('checked');
            }

            element.bind('click', function(){ scope.$apply(toggle); });

            if (scope.checked == 'false' || scope.checked == undefined) {
                scope.checked = false;
                input.removeAttribute('checked');
            } else {
                scope.checked = true;
                input.setAttribute('checked', '');
            }

            scope.$watch('model', function(val){
                if(val == undefined || !val){ 
                    scope.model= false;
                    input.removeAttribute('checked');
                    return;
                }else{
                    scope.checked = true;
                    input.setAttribute('checked', '');
                }
            });
        }
    };

});

directives.directive("semDropdown", function(){
    var dir = {
    restrict: "A",
    scope:{
        on: "@"
    },

    link: function($scope, elem, attr){
        $(elem).dropdown({on: $scope.on? $scope.on:'click',})
    }

    };
    return dir;

});

directives.directive("semDropdown2", function(){
return {
    restrict: "A",
    replace: true,
    transclude: true,
    template: '<div class="ui selection dropdown" > <i class="dropdown icon"></i> Test Drop <div class="menu ui transition hidden">'+ 
                    '<div class="item">Action</div>'+
                    '<div class="item">Action</div>'+
                    '<div class="item">Action</div>'+
                    '</div>',
    scope:{
        on: "@"
    },

    link: function($scope, elem, attr){
        $(elem).dropdown({on: $scope.on? $scope.on:'click',})
    }

    };

});


directives.directive("semTabs", function(){
    return {
    restrict: 'E',
    transclude: true,
    templateUrl:  "/part/directives/tabs.html",
    require: '^semTabs',
    replace: true,
    priority: 10,
    scope: {isRoot: '@', },
    controller: function($scope){
        this.index = 0;
        this.itemsCount = 0;
        $scope.red = true;

        var tabs = $scope.tabs = [];

        if($scope.isRoot){
            $scope.css = 'pointing four item teal ';
        }else{
            $scope.css = 'pointing secondary ';
        }

        $scope.select = function(tab){
            angular.forEach(tabs, function(tab){
                tab.selected = false;
            });
            tab.selected = true;
        };

        //keep track of menu items of each tab
        this.addItem = function(item){
            item.index = this.itemsCount ++;
        }

        this.addTab = function(tab){
            if(tabs.length ===0){
                $scope.select(tab);
                tab.first = true;
                //todo: check if this will be accurate or need callback to update the index
            }
            tab.index = this.index ++;
            tab.uuid = generateUUID();
            tabs.push(tab);
        };

    },

    link: { 
        pre: function(scope, element, attrs, tabsCtrl){
        },
        
        post: function(scope, element, attrs, tabsCtrl){
            //this is the super parent tab set tag
        }
        
    },

    };
});

directives.directive("semTab", function(){
    return {
    require: '^semTabs',
    restrict: 'E',
    transclude: true,
    replace: true,
    templateUrl:  "/part/directives/tab.html",
    scope: {
        title: '@',
        dataTab: '=',
    },

    link: function(scope, element, attrs, tabsCtrl){
        tabsCtrl.addTab(scope);

        if(scope.index == 0){
            element.addClass('active');
        }
    },
    
    }



})


.directive('tabItem', function(){
    return {
    restrict: 'A',
    require: '^semTabs',
    scope: {
        tabItem: '=',
    },

    link: function(scope, element, attrs, tabsCtrl){

        tabsCtrl.addItem(scope);

        if(scope.index == 0){
            element.addClass('active');
        }

        //used element.ready instead of scope.$watch below
        element.ready(function(){
            element.tab({context: element.parent().parent()})
        });

        /*
        scope.$watch('tabItem', function(newVal, oldVal){
            console.log("tabItem rendered...");
            element.tab({context: element.parent().parent()})
            //element.tab({context: $('.tabs')})
        });
        */
    },
    };

})

.directive('chosen', [function($scope){
    return {
restrict: 'A',
link: function(scope, element, attrs){
    //scope.$watch(scope.chosen, function(){
    scope.$watch(attrs.chosen, function(){
        element.trigger('chosen:updated');
    }, true);

    scope.$watchCollection(attrs.ngModel, function(n, o){
        element.trigger('chosen:updated');
    }, true);

    var chosen = element.chosen({
        no_results_found: 'No results found!', 
        enable_split_word_search: true,
        //allow_single_deselect: true,
        search_contains: true,
    });
},


    }; //return

}])

